package com.young.config;

import com.google.gson.internal.Primitives;
import com.young.context.ContextEnvironmentTool;
import com.young.context.SelectorLocalizer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @description：
 * @author: yangyahui01
 * @date: 11/26/24 10:40 AM
 */
public class YoungScheduleClientPropertyLocator {

    protected static final Log LOGGER = LogFactory.getLog(YoungScheduleClientPropertyLocator.class);

    private final Map<String, Object> source = new HashMap<>(16);

    private static final String[] RESOURCES = {"yschedule-client-selector.properties"};

    private final Environment environment;


    public YoungScheduleClientPropertyLocator(Environment environment) {
        this.environment = environment;

        locate(this.environment);
    }

    private void locate(Environment environment) {
        Assert.notNull(environment, "environment argument is required in YoungScheduleClientPropertyLocator's locate method");

        source.putAll(locateProperties(environment));


    }

    private Map<? extends String, ?> locateProperties(Environment environment) {
        Map<String, Object> container = new HashMap<>(16);

        String profile = ContextEnvironmentTool.preferProfile(environment); // 当前环境

        String cloud = ContextEnvironmentTool.cloud(environment); //当前部署平台

        try {
            //首先加载框架本身指定的selector文件
            for (String item : RESOURCES) {
                ClassPathResource resource = new ClassPathResource(item);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                container.putAll(SelectorLocalizer.localize(properties, profile, cloud));
            }
        } catch (Exception e) {
            LOGGER.error("框架selector引导配置文件加载失败，系统将退出..", e);
            throw new IllegalStateException("框架selector引导配置文件加载失败，系统将退出..", e);
        }

        return container;
    }

    public <T> T getProperty(String key, Class<T> classOfT) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        Object value = environment.getProperty(key);
        return value == null ? (T) source.get(key) : Primitives.wrap(classOfT).cast(value);
    }




}
